<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item v-if="isShowQuery" label="选择患者" prop="itemName" style="float: left">
          <bed-vs-patient-into-select :bed-blank="'Y'" :clearable="true"
                                      :org-id="userInfo.orgId"
                                      :visit-id="queryParams.visitId" :ward-code="currentSelectDept" class="width-120"
                                      @bed-change="bedChange"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="packItemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入项目名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="收费项目名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入收费项目名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          @click="handleAdd"
        >
          <template
            #icon>
            <i-ep-plus/>
          </template>
          录入费用
        </el-button>
      </el-col>
    </el-row>
    <el-table v-adaptive="340" :border="true" :data="nurseBillDetailList" :header-cell-style="$headerCellStyle"
              :stripe="true" highlight-current-row>
      <el-table-column :align="'center'" fixed="left" label="费用发生时间" prop="medicalVerifyTime" width="170">
        <template #default="scope">
          <span class="ys-css">{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column :align="'center'" :show-overflow-tooltip='true' fixed="left" label="医嘱内容"-->
      <!--                       prop="orderText" width="120"/>-->
      <el-table-column :align="'center'" fixed="left" label="项目类型" prop="itemClass" width="70">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['bill_item_class_dict']" :value="scope.row.itemClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" label="项目名称"
                       prop="itemName"/>
      <!--            <el-table-column :align="'center'" label="项目编码" prop="itemCode"/>-->
      <el-table-column :align="'left'" header-align="center" label="数量" prop="amount" width="100">
        <template #default="scope">
                    <span
                      :class="scope.row.amount >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        parseFloat(scope.row.amount.toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
        </template>
      </el-table-column>
      <el-table-column :align="'right'" header-align="center" label="单价(元)" prop="itemPrice" width="110">
        <template #default="scope">
          <span class="ys-css">{{ parseFloat(scope.row.itemPrice.toString()).toFixed(2) }}</span>元
        </template>
      </el-table-column>
      <!--            <el-table-column :align="'right'" header-align="center" label="应付费用(元)" prop="costs" width="110">-->
      <!--                <template #default="scope">-->
      <!--                    <span class="ys-css">{{ parseFloat(scope.row.costs.toString()).toFixed(2) }}</span>元-->
      <!--                </template>-->
      <!--            </el-table-column>-->
      <el-table-column :align="'right'" header-align="center" label="实收费用(元)" prop="charges" width="110">
        <template #default="scope">
                    <span :class="scope.row.charges >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        parseFloat(scope.row.charges.toString()).toFixed(2)
                      }}</span>元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="费用来源" prop="sourceType" width="100"/>
      <el-table-column :align="'center'" label="项目规格" prop="itemSpec" width="120"/>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="100"/>
      <el-table-column :align="'center'" label="开单医生" prop="applyDoctorName" width="100"/>
      <el-table-column :align="'center'" label="执行科室" prop="implementDeptName" width="100"/>
      <el-table-column :align="'center'" label="收据分类" prop="classOnInpName" width="100"/>
      <el-table-column :align="'center'" label="结算序号" prop="feesNo" width="100"/>
      <el-table-column :align="'center'" label="患者所在科室" prop="deptStayedName" width="100"/>
      <el-table-column :align="'center'" label="患者所在病区" prop="wardCodeName" width="100"/>
      <el-table-column :align="'center'" label="医保是否上传" prop="isUpload" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isUpload"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改患者固定费用配置对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="30%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="packItemName">
          <el-input v-if="isShow" v-model="form.packItemName"
                    @focus="isShowItemNameFocus()" >
          </el-input>
          <automatic-completion
            v-else ref="itemAutomatic"
            v-model="form.packItemName" :dict-array="dictArray"
            :table-body-list="tableBodyList"
            :table-head-list="tableHeadList"
            :title="itemTitle"
            :width="900"
            style="width: 100%"
            @itemNameInput="itemNameInput"
            @row-click="rowClick"
          />
        </el-form-item>
        <el-form-item label="规格" prop="itemSpec">
          <el-input v-model="form.itemSpec" :disabled="true"/>
        </el-form-item>
        <el-form-item label="单位" prop="units">
          <el-select v-model="form.units" :disabled="true">
            <el-option
              v-for="dict in dictDataMap['spec_unit']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="itemPrice">
          <el-input v-model="form.itemPrice" :disabled="true" placeholder="单价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" @blur="amountBlur"/>
        </el-form-item>
        <el-form-item label="应付费用" prop="costs">
          <el-input v-model="form.costs" :disabled="true" placeholder="应付费用">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="开单科室" prop="applyDept">
          <dept-list v-model="form.applyDept" :clinic-vs-visit-str="'1,2'" :dept-id="form.applyDept"
                     :org-id="userInfo.orgId" :placeholder="'请选择开单科室'"
                     style="width: 100%" @dept-change="applyDeptChange"
          />
        </el-form-item>
        <el-form-item label="开单人" prop="applyDoctor">
          <el-select v-model="form.applyDoctor" placeholder="请选择"
                     style="width: 100%">
            <el-option v-for="item in orgVsDoctorList" :key="item.userId" :label="item.nickName"
                       :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="执行科室" prop="implementDept">
          <dept-list v-model="form.implementDept" :clinical-sign-str="'3'" :dept-id="form.implementDept"
                     :org-id="userInfo.orgId" :placeholder="'请选择执行科室'"
                     style="width: 100%" @dept-change="implementDeptChange"
          />
        </el-form-item>
        <el-form-item label="执行人" prop="implementUser">
          <el-select v-model="form.implementUser" placeholder="请选择"
                     style="width: 100%">
            <el-option v-for="item in orgVsNurseList" :key="item.userId" :label="item.nickName"
                       :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                  <el-button type="primary" @click="submitForm">确 定</el-button>
                  <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {addNurseBillDetail, selectPageInpBillDetail} from "@/api/hospitalization/inpBillDetail.ts";
import {clinicTableHeadList, jsonStrInObj} from "@/utils/autoComplete.ts";
import {getDeptVsUserInfo} from "@/api/system/dept.ts";
import {autoBuildQuery} from "@/api/base/clinicItemDict.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'bill_item_class_dict', 'sys_yes_no'))

const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
const title = ref("");
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

const nurseBillDetailList = ref([])
// 选中科室下医生list
const orgVsDoctorList = ref<any>([])
// 选中执行科室下护士list
const orgVsNurseList = ref<any>([])
const itemAutomatic = ref();
const total = ref(0);
const open = ref(false);
const formRef = ref();
const props = defineProps({
  showParams: {
    type: Object,
    default: {}
  },
  isShowQuery: {
    type: Boolean,
    default: true
  }
})

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  itemName: "",
  visitId: "",
  patientId: ""
})

const autoForm = ref<any>({
  clinicItemName: "",
  itemInfo: "",
  orgId: userInfo.orgId,
  isFiltrationContrastExist: true,
  notInSelect: [],
});

const form = ref<any>({
  visitId: props.showParams.visitId,
  patientId: props.showParams.patientId,
  clinicItemId: "",
  packItemName: "",
  itemName: "",
  itemSpec: "",
  units: "",
  itemPrice: "",
  amount: 0,
  costs: "",
  priceId: "",
  remarks: "",
  chargeCoefficient: "",
  unitsName: "",
  orgId: userInfo.orgId,
  applyDept: props.showParams.deptStayed,
  applyDoctor: props.showParams.doctorInCharge,
  applyDeptName: props.showParams.deptStayedName,
  applyDoctorName: props.showParams.doctorInChargeName,
  implementDept: props.showParams.wardCode,
  implementUser: props.showParams.dutyNurse,
  implementDeptName: props.showParams.wardCodeName,
  implementUserName: props.showParams.dutyNurseName,
})

const rules = ref({
  amount: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  applyDept: [
    {
      required: true, message: "开单科室不能为空", trigger: "blur"
    }
  ],
  packItemName: [
    {
      required: true, message: "项目不能为空", trigger: "change"
    }
  ],
  applyDoctor: [
    {
      required: true, message: "开单人不能为空", trigger: "blur"
    }
  ],
  implementDept: [
    {
      required: true, message: "执行科室不能为空", trigger: "blur"
    }
  ],
  implementUser: [
    {
      required: true, message: "执行人不能为空", trigger: "blur"
    }
  ],
})

/**
 * 切换患者select 点击事件
 * @param obj
 */
function bedChange(obj) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  getList()
}


/** 查询患者固定费用配置列表 */
function getList() {
  if (queryParams.value.visitId) {
    selectPageInpBillDetail(queryParams.value).then((response: any) => {
      nurseBillDetailList.value = response.rows;
      total.value = response.total;
    });
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  getList();
}


// 开单科室下拉选择事件
function applyDeptChange(value: any) {
  form.value.applyDept = value.deptId
  getOrgVsDoctorListFun()
}

// 开单人查询
function getOrgVsDoctorListFun() {
  if (form.value.applyDept) {
    getDeptVsUserInfo({deptId: form.value.applyDept}).then((res: resType) => {
      orgVsDoctorList.value = res.data
    })
  } else {
    orgVsDoctorList.value = []
  }
}

// 执行科室下拉选择事件
function implementDeptChange(value: any) {
  form.value.implementDept = value.deptId
  getOrgVsNurseListFun()
}


// 执行人人查询
function getOrgVsNurseListFun() {
  if (form.value.implementDept) {
    getDeptVsUserInfo({deptId: form.value.implementDept}).then((res: resType) => {
      orgVsNurseList.value = res.data
    })
  } else {
    orgVsNurseList.value = []
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    inpBillDetailId: "",
    visitId: queryParams.value.visitId,
    patientId: queryParams.value.patientId,
    clinicItemId: "",
    packItemName: "",
    itemName: "",
    itemSpec: "",
    units: "",
    itemPrice: "",
    amount: 1,
    costs: "",
    priceId: "",
    orgId: userInfo.orgId,
    applyDept: props.showParams.deptStayed,
    applyDoctor: props.showParams.doctorInCharge,
    applyDeptName: props.showParams.deptStayedName,
    applyDoctorName: props.showParams.doctorInChargeName,
    implementDept: props.showParams.wardCode,
    implementUser: props.showParams.dutyNurse,
    implementDeptName: props.showParams.wardCodeName,
    implementUserName: props.showParams.dutyNurseName,
  }
  nextTick(() => {
    formRef.value.resetFields()
  })
}


/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName;
  getListClinicItemDict();

}

/** 自动补全后台查询 */
function getListClinicItemDict() {
  if (autoForm.value.itemInfo) {
    // form.value.notInSelect = ['A', 'B', 'F', 'C', 'D', 'E', 'F', 'G', 'H']
    autoForm.value.notInSelect = ["A", "B"];
    autoForm.value.orgId = userInfo.orgId;
    // 是否过滤已存在的项目标记
    autoForm.value.isFiltrationContrastExist = true;
    autoBuildQuery(autoForm.value).then((res) => {
      tableBodyList.value = res.data;
      // 打开自动补全弹出框
      itemAutomatic.value.init();
    });
  } else {
    tableBodyList.value = [];
  }
}


/** 项目列表行点击事件 */
function rowClick(row: any) {
  itemAutomatic.value.closePopover();
  isShow.value = true
  form.value.clinicItemId = row.clinicItemId;
  form.value.packItemName = row.itemName;
  form.value.itemSpec = row.itemSpec;
  form.value.itemClass = row.itemClass;
  autoForm.value.clinicItemName = row.itemName;
  const subTotal = row.subTotal ? row.subTotal : 0;
  form.value.itemPrice = subTotal.toFixed(2);
  form.value.costs = (subTotal * form.value.amount).toFixed(2);
  tableBodyList.value = [];
}


/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.packItemName)
    itemAutomatic.value.focusInput()
  })
}


/**
 * 开单数量input焦点消失时间
 */
function amountBlur() {
  form.value.costs = (Number(form.value.amount) * Number(form.value.itemPrice)).toFixed(2);
}

/**
 * 录入费用
 */
function handleAdd() {
  open.value = true;
  reset();
  getOrgVsDoctorListFun()
  getOrgVsNurseListFun()
  title.value = "录入患者固定费用";
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      addNurseBillDetail(form.value).then(() => {
        ElMessage.success("录入成功");
        open.value = false;
        closePopover()
        getList();
      }).finally(() => {
      });
    }
  });
}

/** 项目选择关闭事件 */
function closePopover() {
  itemAutomatic.value.itemNameEmpty();
  tableBodyList.value = [];
}

function initOpen(obj: any) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  handleQuery()
}

defineExpose({
  initOpen
})
</script>


<style scoped>

</style>
